package com.af.community.smart.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.af.community.smart.base.*
import com.af.community.smart.business.PeopleAddActivity
import com.af.community.smart.business.R
import com.af.community.smart.model.CityData
import com.af.community.smart.model.PeopleData
import com.af.community.smart.share.Const
import com.af.community.smart.utils.*
import com.af.community.smart.utils.DialogHelper.showCityDialog
import com.af.community.smart.utils.DialogHelper.showDateDialog
import com.af.community.smart.utils.DialogHelper.showItemDialog
import com.af.community.smart.utils.DialogHelper.showListDialog
import com.af.community.smart.viewmodel.PeopleViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.matisse.Matisse
import com.lxj.matisse.MimeType
import com.sunfusheng.GlideImageView
import kotlinx.android.synthetic.main.fragment_people_second.*
import net.idik.lib.slimadapter.SlimAdapter
import org.koin.androidx.viewmodel.ext.android.getViewModel
import java.util.*
import kotlin.collections.ArrayList

class PeopleSecondFragment : BaseFragment() {

    private var mGridId = ""    //网格id
    private var mSex = ""       //性别
    private var mNation = ""    //民族
    private var mhType = ""     //户口类型
    private var mIn = ""        //流入时间
    private var nzType = ""     //住房类型
    private var nPlace = ""     //籍贯
    private var nBirth = ""     //出生日期
    private var nAvatar = ""    //上传图片
    private var nCulture = ""   //文化程度
    private var nRelation = ""  //户主关系
    private var nLevel = ""     //职称等级
    private var nReason = ""    //居住事由
    private var nState = ""     //登记证
    private var nTime = ""      //登记日期
    private var nEnd = ""       //到期日期
    private var nCan = ""       //是否残疾
    private var nDi = ""        //是否低保
    private var nShi = ""       //是否实业
    private var nProve = ""     //上传证明

    private val list = ArrayList<String>()
    private val cityList = ArrayList<CityData>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_people_second, container, false)
    }

    override fun getViewModel() = getViewModel<PeopleViewModel>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mGridId = getString("gridId")
        people_grid.text = getString("gridName")

        mAdapter.updateData(list.apply { add("") })

        activity?.observe("people_prove") { img ->
            if (mPosition < 0) {
                list.remove("")
                list.add(0, img)
                nProve = list.joinToString(",")
                if (list.size < 3) list.add(0, "")
                mAdapter.notifyDataSetChanged()
            } else {
                list.removeAt(mPosition)
                list.add(mPosition, img)
                nProve = list.filter { it.isNotEmpty() }.joinToString(",")
                mAdapter.notifyDataSetChanged()
            }
        }

        activity?.observe("people_avatar") {
            nAvatar = it
            peopoe_img.loadRoundedImage(it.scaleImage())
        }
    }

    override fun initTitle() {
        val mData = arguments?.getSerializable("data") as PeopleData?
        if (mData != null) {
            bt_sure.gone()

            mSex = mData.sex.orEmpty()
            mNation = mData.national.orEmpty()
            nBirth = mData.birthday.orEmpty()
            people_name.setText(mData.userName)
            people_sex.text = when (mSex) {
                "0" -> "女"
                "1" -> "男"
                else -> ""
            }
            people_nation.text = mNation
            people_birth.text = nBirth
            people_id.setText(mData.account)
        }

        img_list.apply {
            layoutManager = LinearLayoutManager(
                activity,
                LinearLayoutManager.HORIZONTAL,
                true
            )
        }

        //上传证明
        mAdapter = SlimAdapter.create()
            .register<String>(R.layout.item_people_img) { data, injector ->

                val index = list.indexOf(data)

                injector.visibility(
                    R.id.item_people_del,
                    if (data.isEmpty()) View.INVISIBLE else View.VISIBLE
                )
                    .with<GlideImageView>(R.id.item_people) {
                    if (data.isEmpty()) it.loadDrawable(R.mipmap.icon_upload)
                    else it.loadRoundedImage(data.scaleImage())
                }
                    .clicked(R.id.item_people) {
                        if (data.isEmpty()) {
                            val selectSize = list.filter { it.isNotEmpty() }.size

                            mPosition = -1
                            Matisse.from(activity)
                                .choose(MimeType.ofImage())
                                .theme(R.style.Matisse_Blue)
                                .capture(true)
                                .originalEnable(false)
                                .maxSelectable(3 - selectSize)
                                .forResult(42)
                        } else {
                            mPosition = index
                            Matisse.from(activity)
                                .choose(MimeType.ofImage())
                                .theme(R.style.Matisse_Blue)
                                .capture(true)
                                .originalEnable(false)
                                .maxSelectable(1)
                                .forResult(42)
                        }
                    }
                    .clicked(R.id.item_people_del) {
                        list.remove(data)
                        mAdapter.notifyItemRemoved(index)
                        mAdapter.notifyItemRangeChanged(index, list.size - index)
                        if ("" !in list) {
                            list.add(0, "")
                            mAdapter.notifyItemInserted(0)
                            mAdapter.notifyItemRangeChanged(0, list.size)
                        }
                    }
            }
            .attachTo(img_list)

        //性别
        people_sex_ll.oneClick {
            activity?.showListDialog(
                "男", "女"
            ) { index, hint ->
                mSex = (1 - index).toString()
                people_sex.text = hint
            }
        }

        //民族
        people_nation_ll.oneClick {
            activity?.showItemDialog(
                "请选择民族",
                Const.nationList.indexOf(mNation),
                Const.nationList
            ) { _, hint ->
                mNation = hint
                people_nation.text = hint
            }
        }

        //户口类型
        people_type_ll.oneClick {
            activity?.showItemDialog(
                "请选择户口类型",
                Const.typeList.indexOf(mhType),
                Const.typeList
            ) { _, hint ->
                mhType = hint
                people_type.text = hint
            }
        }

        //流入时间
        people_in_ll.oneClick {
            val calendar = Calendar.getInstance()
            val yearNow = calendar.get(Calendar.YEAR)
            activity?.showDateDialog(
                maxYearValue = yearNow,
                count = 3,
                title = "请选择流入时间",
                isAfterLimited = true,
                callback = { _, _, _, _, _, hint ->
                    mIn = "$hint 00:00:00"
                    people_in.text = hint
                }
            )
        }

        //住房类型
        people_ztype_ll.oneClick {
            activity?.showListDialog(
                "集体生活住房", "集体房", "出租房",
                "闲置房", "生产经营房", "其他"
            ) { _, hint ->
                nzType = hint
                people_ztype.text = hint
            }
        }

        //籍贯
        people_place_ll.oneClick {
            if (cityList.isEmpty()) {
                getViewModel().getCityData(activity!!)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribe {
                        cityList.addItems(it)
                        if (cityList.isNotEmpty()) {
                            activity?.showCityDialog(
                                title = "请选择籍贯",
                                list = cityList,
                                listener = { province, city, area, _, _, _ ->
                                    nPlace = "$province $city $area"
                                    people_place.text = nPlace
                                }
                            )
                        }
                    }
            } else {
                activity?.showCityDialog(
                    title = "请选择籍贯",
                    list = cityList,
                    listener = { province, city, area, _, _, _ ->
                        nPlace = "$province $city $area"
                        people_place.text = nPlace
                    }
                )
            }
        }

        //出生日期
        people_birth_ll.oneClick {
            val calendar = Calendar.getInstance()
            val yearNow = calendar.get(Calendar.YEAR)
            activity?.showDateDialog(
                maxYearValue = yearNow,
                count = 3,
                title = "请选择出生日期",
                isAfterLimited = true,
                callback = { _, _, _, _, _, hint ->
                    nBirth = hint
                    people_birth.text = hint
                }
            )
        }

        //上传图片
        peopoe_img.oneClick {
            Matisse.from(activity)
                .choose(MimeType.ofImage())
                .theme(R.style.Matisse_Blue)
                .capture(true)
                .originalEnable(false)
                .maxSelectable(1)
                .forResult(52)
        }

        //文化程度
        people_culture_ll.oneClick {
            activity?.showListDialog(
                "文盲", "小学", "初中", "高中", "中专",
                "大专", "本科", "研究生", "博士"
            ) { _, hint ->
                nCulture = hint
                people_culture.text = hint
            }
        }

        //户主关系
        people_relation_ll.oneClick {
            activity?.showItemDialog(
                "请选择与户主关系",
                Const.relationList.indexOf(nRelation),
                Const.relationList
            ) { _, hint ->
                nRelation = hint
                people_relation.text = hint
            }
        }

        //职称等级
        people_level_ll.oneClick {
            activity?.showListDialog(
                "高级", "中级", "初级", "高级技师", "技师",
                "高级工", "中级工", "初级工", "无等级"
            ) { _, hint ->
                nLevel = hint
                people_level.text = hint
            }
        }

        //居住事由
        people_reason_ll.oneClick {
            activity?.showListDialog(
                "务工", "务农", "经商", "盲流", "其他"
            ) { _, hint ->
                nReason = hint
                people_reason.text = hint
            }
        }

        //登记情况
        people_state_ll.oneClick {
            activity?.showListDialog(
                "登记类", "临时居住证", "居住证"
            ) { _, hint ->
                nState = hint
                people_state.text = hint
            }
        }

        //登记日期
        people_time1_ll.oneClick {
            val calendar = Calendar.getInstance()
            val yearNow = calendar.get(Calendar.YEAR)
            activity?.showDateDialog(
                maxYearValue = yearNow,
                count = 3,
                title = "请选择登记日期",
                isAfterLimited = true,
                callback = { _, _, _, _, _, hint ->
                    nTime = "$hint 00:00:00"
                    people_time1.text = hint
                }
            )
        }

        //到期日期
        people_time2_ll.oneClick {
            val calendar = Calendar.getInstance()
            val yearNow = calendar.get(Calendar.YEAR)
            activity?.showDateDialog(
                minYearValue = yearNow,
                count = 3,
                title = "请选择预计到期日期",
                isBeforeLimited = true,
                callback = { _, _, _, _, _, hint ->
                    nEnd = "$hint 00:00:00"
                    people_time2.text = hint
                }
            )
        }

        //是否残疾
        people_can_ll.oneClick {
            activity?.showListDialog(
                "是", "否"
            ) { index, hint ->
                nCan = if (index == 0) "201" else ""
                people_can.text = hint
            }
        }

        //是否低保
        people_di_ll.oneClick {
            activity?.showListDialog(
                "是", "否"
            ) { index, hint ->
                nDi = if (index == 0) "202" else ""
                people_di.text = hint
            }
        }

        //是否失业
        people_shi_ll.oneClick {
            activity?.showListDialog(
                "是", "否"
            ) { index, hint ->
                nShi = if (index == 0) "205" else ""
                people_shi.text = hint
            }
        }

        //提交
        bt_sure.oneClick { getAddData() }
    }

    fun getAddData() {
        when {
            mGridId.isEmpty() -> {
                showToast("请选择所属网格")
                return
            }
            people_znum.text.isBlank() -> {
                people_znum.requestFocus()
                showToast("请输入住房编号")
                return
            }
            people_hnum.text.isBlank() -> {
                people_hnum.requestFocus()
                showToast("请输入户口编号")
                return
            }
            people_name.text.isBlank() -> {
                people_name.requestFocus()
                showToast("请输入姓名")
                return
            }
            mSex.isEmpty() -> {
                showToast("请选择性别")
                return
            }
            mNation.isEmpty() -> {
                showToast("请选择民族")
                return
            }
            people_id.text.isEmpty() -> {
                people_id.requestFocus()
                showToast("请输入身份证号")
                return
            }
            mhType.isEmpty() -> {
                showToast("请选择户口类型")
                return
            }
            mIn.isEmpty() -> {
                showToast("请选择流入时间")
                return
            }
            people_tel1.text.isEmpty() -> {
                people_tel1.requestFocus()
                showToast("请输入联系手机")
                return
            }
            !CommonUtil.IDCardValidate(people_id.textString()) -> {
                people_id.requestFocus()
                showToast("请输入正确的身份证号")
                return
            }
            !people_tel1.textString().isMobile() -> {
                people_tel1.requestFocus()
                showToast("请输入正确的联系手机")
                return
            }
            people_mid.text.isNotEmpty()
                    && !CommonUtil.IDCardValidate(people_mid.textString()) -> {
                people_mid.requestFocus()
                showToast("请输入正确的房主身份证号")
                return
            }
            people_tel2.text.isNotEmpty()
                    && !people_tel2.textString().isTel() -> {
                people_tel2.requestFocus()
                showToast("请输入正确的单位电话")
                return
            }
        }

        val specialList = ArrayList<String>()
        if (nCan.isNotEmpty()) specialList.add(nCan)
        if (nDi.isNotEmpty()) specialList.add(nDi)
        if (nShi.isNotEmpty()) specialList.add(nShi)

        getViewModel().getAddData(
            "status" to 1,
            "checkUserId" to getString("userId"),
            "baseType" to 2,
            "gridId" to mGridId,
            "gridName" to people_grid.textString(),
            "housNumber" to people_znum.trimString(),
            "doorNumber" to people_hnum.trimString(),
            "userName" to people_name.trimString(),
            "sex" to mSex,
            "national" to mNation,
            "account" to people_id.textString(),
            "residenceType" to mhType,
            "intotime" to mIn,
            "phone" to people_tel1.textString(),

            "housType" to nzType,
            "owner" to people_mname.trimString(),
            "ownerID" to people_mid.textString(),
            "zoneNumber" to people_lnum.trimString(),
            "birthplace" to nPlace,
            "birthday" to nBirth,
            "avatar" to nAvatar,
            "education" to nCulture,
            "relation" to nRelation,
            "titleLevel" to nLevel,
            "toLiveFor" to nReason,
            "temporaryResidence" to nState,
            "temporarySignTime" to nTime,
            "temporaryEndTime" to nEnd,
            "address" to people_addr1.trimString(),
            "professional" to people_job.trimString(),
            "workName" to people_unit.trimString(),
            "workAddress" to people_addr2.trimString(),
            "workTel" to people_tel2.textString(),
            "specialType" to specialList.joinToString(","),
            "prove" to nProve,
            "remark" to people_memo.trimString()
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByNoError(
                event = getViewModel(),
                onSuccess = {
                    showToast("人口信息添加成功！")
                    LiveEventBus.get("people_check").post("done")
                    ActivityStack.screenManager.popActivities(PeopleAddActivity::class.java)
                }
            )
    }

}
